package common

import (
	"database/sql/driver"
	"fmt"
	"strings"
	"time"
)

const (
	//年月日时分秒格式
	YY_MM_DD_H_I_S = "2006-01-02 15:04:05"
	YY_MM_DD_H_0I  = "2006-01-02 15:04"
	YY_MM_DD       = "2006-01-02"
)

// LocalTime 别名
type LocalTime time.Time

//func setFormat(string format) string {
//	return ""
//}
//func getFormat() string {
//	return ""
//}
func (t LocalTime) MarshalJSON() ([]byte, error) {
	tTime := time.Time(t)
	return []byte(fmt.Sprintf("\"%v\"", tTime.Format(YY_MM_DD_H_I_S))), nil
}

func (t LocalTime) Value() (driver.Value, error) {
	// LocalTime 转换成 time.Time 类型
	tTime := time.Time(t)
	return tTime.Format(YY_MM_DD_H_I_S), nil
}

func (t *LocalTime) UnmarshalJSON(data []byte) error {
	if string(data) == "null" {
		return nil
	}
	var err error
	//前端接收的时间字符串
	str := string(data)
	//去除接收的str收尾多余的"
	timeStr := strings.Trim(str, "\"")
	t1, err := time.Parse(YY_MM_DD_H_I_S, timeStr)
	*t = LocalTime(t1)
	return err
}

func (t *LocalTime) Scan(v interface{}) error {
	if value, ok := v.(time.Time); ok {
		*t = LocalTime(value)
		return nil
	}
	return fmt.Errorf("can not convert %v to timestamp", v)
}
